from flask import request, g, current_app as app
from flask_jwt_extended import get_jwt, verify_jwt_in_request, get_jwt_identity
import time

EXCLUDE_TENANT_PATHS = ['/api/admin/login', '/login', '/glogin']


def register_middlewares(app):
    @app.before_request
    def before_request():
        g.start_time = time.time()
        real_ip = request.headers.get('X-Forwarded-For', request.remote_addr)

        # 初始化租户相关变量
        g.tenant_id = None
        g.is_super_admin = False
        g.skip_tenant_check = False

        # 对于排除路径，跳过租户检查
        if request.path in EXCLUDE_TENANT_PATHS or request.path.startswith('/static'):
            g.skip_tenant_check = True
        else:
            # 尝试从JWT获取租户信息
            try:
                verify_jwt_in_request(optional=True)
                claims = get_jwt()
                if claims:
                    g.tenant_id = claims.get('tenant_id')
                    g.is_super_admin = claims.get('role') == 'super_admin'

                    # 如果JWT中没有租户信息，尝试从HTTP头获取
                    if g.tenant_id is None:
                        g.tenant_id = request.headers.get('X-Tenant-ID', type=int)
            except Exception:
                # JWT验证失败，尝试从HTTP头获取
                g.tenant_id = request.headers.get('X-Tenant-ID', type=int)
        # 记录租户ID信息（用于调试）
        if request.path != '/upload64':
            app.logger.info(
                f'🔍 请求路径: {request.path}, 当前租户ID: {g.tenant_id}, 超级管理员: {g.is_super_admin}, 跳过检查: {g.skip_tenant_check}')

        if request.path != '/upload64':
            app.logger.info(f'请求开始: {request.method} {request.path} - IP: {real_ip} - 参数: {dict(request.args)}')
            if request.is_json:
                json_data = request.get_json(silent=True)
                if json_data:
                    app.logger.info(f'请求JSON数据: {json_data}')

    @app.after_request
    def after_request(response):
        diff = time.time() - g.start_time
        app.logger.info(
            f'请求结束: {request.method} {request.path} - 耗时: {diff:.4f}秒 - 状态码: {response.status_code}')
        origin = request.headers.get('Origin')
        if origin:
            response.headers['Access-Control-Allow-Origin'] = origin
            response.headers['Access-Control-Allow-Credentials'] = 'true'
        response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization,X-Requested-With'
        response.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS,PATCH'
        return response
